<template>
  <el-dialog
    ref="wkDialog"
    :visible="visible"
    :before-close="closeClick"
    :close-on-click-modal="false"
    append-to-body
    title="客户关系"
    width="620px"
    @close="closeClick">
    <relevance-enterprise
      :id="id"
      v-model="dataValue"
      show-tips
    />
    <template slot="footer">
      <el-button
        type="primary"
        @click="saveClick">保存</el-button>
      <el-button @click="closeClick">取消</el-button>
    </template>
  </el-dialog>
</template>
<script type="text/javascript">
import { crmCustomerAffiliateCustomerAPI } from '@/api/crm/customer'

import RelevanceEnterprise from './RelevanceEnterprise'

import ElDialogLoadingMixin from '@/mixins/ElDialogLoading'
import { objDeepCopy } from '@/utils'

export default {
  name: 'RelevanceEnterpriseDialog',
  components: { RelevanceEnterprise }, // 关联客户关系
  mixins: [ElDialogLoadingMixin],
  props: {
    visible: {
      type: Boolean,
      required: true,
      default: false
    },
    // 模块ID
    id: [String, Number],
    // 已有数据
    data: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      loading: false,
      dataValue: []
    }
  },
  mounted() {
    this.dataValue = objDeepCopy(this.data)
  },
  methods: {
    /**
     * @description: 取消选择
     * @return {*}
     */
    closeClick() {
      this.$emit('update:visible', false)
    },

    /**
     * @description: 确认选择
     * @return {*}
     */
    saveClick() {
      for (let i = 0; i < this.dataValue.length; i++) {
        const element = this.dataValue[i]
        if (!element.relationsId) {
          return this.$message.error('请完善客户信息')
        } else if (element.sourceCustomerId === element.targetCustomerId) {
          return this.$message.error('关联客户不能是当前客户')
        }
      }
      const list = []
      this.dataValue.forEach(item => {
        list.push({
          customerId: item.sourceCustomerId,
          relationsId: item.relationsId,
          relationsName: item.relationsName,
          relationsType: item.relationsType,
          targetCustomerId: [item.targetCustomerId]
        })
      })

      this.loading = true
      crmCustomerAffiliateCustomerAPI({
        id: this.id,
        list
      })
        .then(res => {
          this.$message.success('操作成功')
          this.$emit('success')
          this.closeClick()
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    }
  }
}
</script>
<style lang="scss" scoped>
.el-dialog__wrapper {
  ::v-deep .el-dialog__body {
    padding-top: 0;
    padding-bottom: 0;
  }

  ::v-deep .el-dialog {
    width: 75% !important;
    max-width: 926px !important;
  }
}
</style>
